package top.hkyzf.study.leetcode.array;

import org.junit.Test;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 朱峰
 * @date 2022-2-14 8:59
 */
public class 两个数组的交集II_350 {
    public int[] intersect(int[] nums1, int[] nums2) {
        Map<Integer, Integer> maps = new HashMap<>();
        int[] result = new int[nums2.length];
        for (int num : nums1) {
            maps.put(num, maps.getOrDefault(num, 0) + 1);
        }
        int index = 0;
        for (int num : nums2) {
            if (maps.containsKey(num)) {
                result[index] = num;
                index++;
                maps.put(num, maps.getOrDefault(num, 0) - 1);
                if (maps.get(num) == 0) {
                    maps.remove(num);
                }
            }
        }
        return Arrays.copyOf(result, index);
    }

    @Test
    public void testIntersect () {
        int[] nums1 = {4,9,5};
        int[] nums2 = {9,4,9,8,4};
        int[] intersect = intersect(nums1, nums2);
        System.out.println(Arrays.toString(intersect));
    }
}
